package com.chenjiagou.ordertickets.controller;

import com.chenjiagou.ordertickets.entity.*;
import com.chenjiagou.ordertickets.service.BookingSeatService;
import com.chenjiagou.ordertickets.service.BookingService;
import com.chenjiagou.ordertickets.service.FlightSeatService;
import com.chenjiagou.ordertickets.service.PassengerService;
import com.chenjiagou.ordertickets.util.IdCardUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.awt.print.Book;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/order")
@Slf4j
public class OrderController {
    @Resource
    FlightSeatService flightSeatService;
    @Resource
    PassengerService passengerService;
    @Resource
    BookingService bookingService;
    @Resource
    BookingSeatService bookingSeatService;
    @GetMapping("/success")
    public String showOrderForm(@RequestParam("flightId") int flightId,
                                @RequestParam("flightNo") String flightNo,
                                @RequestParam("basePrice") double basePrice,
                                @RequestParam("depPort") String depPort,
                                @RequestParam("arrPort") String arrPort,
                                @RequestParam("departureCity") String departureCity,
                                @RequestParam("arrivalCity") String arrivalCity,
                                @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date departureDate,
                                @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date returnDate,
                                @RequestParam(required = false, defaultValue = "false") boolean roundTrip,
                                Model model) {
        log.info("flight:{}",flightId);
        log.info("flightNo:{}",flightNo);
        log.info("basePrice:{}",basePrice);
        log.info("depPort:{}",depPort);
        log.info("arrPort:{}",arrPort);
        log.info("departureCity:{}",departureCity);
        log.info("arrivalCity:{}",arrivalCity);
        log.info("departureDate:{}",departureDate);
        log.info("returnDate:{}",returnDate);
        log.info("roundTrip:{}",roundTrip);
        model.addAttribute("flightId", flightId);
        model.addAttribute("flightNo", flightNo);
        model.addAttribute("basePrice", basePrice);
        model.addAttribute("depPort", depPort);
        model.addAttribute("arrPort", arrPort);

        // ✅ 新增查询参数传给前端
        model.addAttribute("departureCity", departureCity);
        model.addAttribute("arrivalCity", arrivalCity);
        model.addAttribute("departureDate", departureDate);
        model.addAttribute("returnDate", returnDate);
        model.addAttribute("roundTrip", roundTrip);

        return "buy"; // buy.html 页面
    }
    @GetMapping("/available")
    @ResponseBody
    public List<String> getAvailableSeats(
            @RequestParam("flightId") Long flightId,
            @RequestParam("seatClassId") Long seatClassId) {
        log.info("Flight ID: {}, Seat Class ID: {}", flightId, seatClassId);
        List<String> availableSeats = flightSeatService.getAvailableSeats(flightId, seatClassId);
        log.info("Available seats: {}", availableSeats);
        return availableSeats;
    }
    @PostMapping("/submit")
    @ResponseBody
    public ResponseEntity<String> submitOrder(@ModelAttribute OrderFormDTO orderForm, Model model) {
        log.info("收到订单提交：{}", orderForm.getOrderNo());
        log.info("航班号：{}", orderForm.getFlightNo());

        for (PassengerOrderDTO p : orderForm.getPassengers()) {
            log.info("乘客姓名：{}，性别：{}，身份证：{}，舱位：{}，座位：{}，金额：{}",
                    p.getFullName(), p.getGender(), p.getIdNo(),
                    p.getCabin(), p.getSeatNo(), p.getAmount());
           boolean isExist = passengerService.queryByGender(1L,p.getFullName(),p.getIdNo());
           if(isExist==false){
               //插入乘客信息
               Passenger passenger = new Passenger();
               passenger.setFullName(p.getFullName());
               passenger.setGender(p.getGender());
               passenger.setIdNo(p.getIdNo());
               Date birthday = IdCardUtils.extractBirthday(passenger.getIdNo());
               passenger.setBirthday(birthday);
               passenger.setPhone(p.getPhone());
               passenger.setCount(1);
               passengerService.insert(passenger);
           }else{
               passengerService.updateByCount(1L,p.getFullName(),p.getIdNo());
           }
           //将座位改为已售状态
            flightSeatService.updateByFlightAndIdNo(orderForm.getFlightId(),p.getSeatNo());
            Booking booking = new Booking();
            booking.setBookingNo(orderForm.getOrderNo());
            booking.setUserId(1L);
            booking.setFlightId(orderForm.getFlightId());
            booking.setSeatClassId(Long.valueOf(p.getCabin()));
            booking.setStatus(2);
            booking.setTotalAmount(p.getAmount());
            bookingService.insert(booking);
            BookingSeat bookingSeat = new BookingSeat();
            bookingSeat.setBookingId(booking.getId());
            bookingSeat.setSeatNo(p.getSeatNo());
            bookingSeat.setPrice(p.getAmount());
            bookingSeatService.insert(bookingSeat);
        }


        return ResponseEntity.ok("success"); // 返回 200 OK


    }
}
